import { login, getInfo } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
const state = {
  token: getToken() || '',
  userInfo: {},
  btnList: []
}

const mutations = {
  setToken: (state, token) => {
    state.token = token
    setToken(token)
  },
  removeToken: (state) => {
    state.token = ''
    removeToken()
  },
  updateUserInfo(state, newInfo) {
    state.userInfo = newInfo
  },
  setBtnList(state, btnList) {
    state.btnList = btnList
  }

}
const actions = {
  async loginAction(context, data) {
    // 发送请求，获取token
    const res = await login(data)
    console.log(res)
    context.commit('setToken', res.data)
    return res
  },

  async getInfoAction(context) {
    const res = await getInfo()
    console.log(res)
    context.commit('updateUserInfo', res.data.userInfo)
    context.commit('setBtnList', res.data.btnList)
    return res.data.menuList
  },

  logoutAction(context) {
    context.commit('removeToken')
    context.commit('updateUserInfo', {})
    // 重置路由
    resetRouter()
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
